<template>
  <div id="myAccount">
    <div class="container">
      <div class="head-line">
        <img src="@/assets/images/titleIcon.png" alt="" />
        {{ $t("account.accountInfo") }}
      </div>
      <div class="personForm">
        <div>
          <div class="personTitle">{{ $t("account.phone") }}</div>
          <div class="personForm-container">
            <el-input
              v-model="queryParams.phonenumber"
              :placeholder="$t('account.enterPhone')"
              disabled
            />
            <div class="createBtn" @click="phoneChange(0)">
              <img src="@/assets/images/change.png" alt="" />{{
                $t("account.alter")
              }}
            </div>
          </div>
        </div>
        <div>
          <div class="personTitle">{{ $t("account.password") }}</div>
          <div class="personForm-container">
            <el-input
              v-model="queryParams.password"
              :placeholder="$t('account.check1')"
              disabled
            />
            <div class="createBtn" @click="phoneChange(1)">
              <img src="@/assets/images/change.png" alt="" />{{
                $t("account.alter")
              }}
            </div>
          </div>
        </div>
        <div>
          <div class="personTitle">{{ $t("account.systemLanguage") }}</div>
          <!--        <el-input-->
          <!--            v-model="queryParams.systemLanguage"-->
          <!--            :placeholder="$t('account.enterSystemLanguage')"-->
          <!--            disabled-->
          <!--        />-->
          <el-select
            v-model="queryParams.systemLanguage"
            :placeholder="$t('account.enterSystemLanguage')"
          >
            <el-option
              v-for="dict in languageList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </div>
      </div>
      <div class="down-container">
        <el-button @click="goBack">{{ $t("account.cancel") }}</el-button>
        <el-button @click="accountConfirm">{{
          $t("account.confirm")
        }}</el-button>
      </div>

      <!-- 身份验证 -->
      <el-dialog
        class="deviceVisible"
        v-model="checkVisible"
        title=""
        width="26%"
        :show-close="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        center
        top="1vh"
      >
        <template #header>
          <div class="title">{{ $t("account.authentication") }}</div>
        </template>
        <div
          style="
            color: rgba(43, 193, 123, 1);
            font-size: 12px;
            text-align: left;
            margin-bottom: 5%;
          "
        >
          {{ $t("account.check2") }}
        </div>
        <el-form :model="authentication" ref="checkRef">
          <el-form-item>
            <el-input
              class="firstCheck"
              v-model="authentication.phone"
              disabled
            />
          </el-form-item>
          <el-form-item
            style="display: flex; justify-content: space-around"
            label=""
            prop="smsCode"
          >
            <el-input
              class="secondCheck"
              v-model="authentication.sms"
              :placeholder="$t('account.SMSVerification')"
              clearable
            />
            <el-button @click="getSmsCode(0, authentication.phone)">
<!--              {{ $t("account.getVerification") }}-->
              <Smscode ref="sms"></Smscode>
            </el-button>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="checkVisible = false">{{
              $t("account.cancel")
            }}</el-button>
            <el-button
              style="background: #2bc17b; color: #ffffff"
              @click="checkConfirm(checkRef)"
            >
              {{ $t("account.check") }}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 更改密码 -->
      <el-dialog
        class="passwordVisible"
        v-model="passwordVisible"
        title=""
        width="26%"
        :show-close="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        center
        top="1vh"
      >
        <template #header>
          <div class="title">{{ $t("account.changePassword") }}</div>
        </template>
        <el-form
          :model="changePassword"
          ref="passwordRef"
          :rules="passwordRules"
        >
          <el-form-item label="新密码" prop="password">
            <el-input
              type="password"
              v-model="changePassword.password"
              :placeholder="$t('account.enterNewPassword')"
              minlength="8"
              maxlength="20"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="passwordAgain">
            <el-input
              type="password"
              v-model="changePassword.passwordAgain"
              :placeholder="$t('account.enterNewPasswordAgain')"
              minlength="8"
              maxlength="20"
              show-password
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="passwordVisible = false">{{
              $t("account.cancel")
            }}</el-button>
            <el-button
              style="background: #2bc17b; color: #ffffff"
              @click="passwordConfirm(passwordRef)"
            >
              {{ $t("account.confirm") }}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 更改手机号码 -->
      <el-dialog
        class="phoneVisible"
        v-model="phoneVisible"
        title=""
        width="26%"
        :show-close="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        center
        top="1vh"
      >
        <template #header>
          <div class="title">{{ $t("account.changePhone") }}</div>
        </template>
        <el-form :model="changePhone" ref="phoneRef" :rules="changePhoneRules">
          <el-form-item prop="phone">
            <el-input
              class="firstCheck"
              v-model="changePhone.phone"
              icon="View"
              maxlength="11"
              :placeholder="$t('account.enterNewChangePhone')"
              clearable
            />
          </el-form-item>
          <el-form-item label="" prop="sms">
            <el-input
              class="secondCheck"
              v-model="changePhone.sms"
              :placeholder="$t('account.SMSVerification')"
              clearable
            />
            <el-button @click="getSmsCode(1, changePhone.phone)">
<!--              {{ $t("account.getVerification") }}-->
              <Smscode ref="sms"></Smscode>
            </el-button>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="phoneVisible = false">{{
              $t("account.cancel")
            }}</el-button>
            <el-button
              style="background: #2bc17b; color: #ffffff"
              @click="phoneConfirm(phoneRef)"
            >
              {{ $t("account.confirm") }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup name="myAccount">
import { onBeforeMount, onMounted, reactive, ref, toRefs } from "vue";
import { ElFormItem, ElInput, ElMessage } from "element-plus";
import { getDicts } from "@/api/system/dict/data";
import {
  getInfo,
  getSmsByPhone,
  getSmsVerify,
  updateUser,
  editPassword,
} from "@/api/account/index.js";
import Smscode from "./smscode.vue";
import { useI18n } from "vue-i18n";
const { locale } = useI18n();
const { proxy } = getCurrentInstance();
import { getCurrentInstance } from "vue";
const { $t } = getCurrentInstance().proxy;
const checkVisible = ref(false);
const passwordVisible = ref(false);
const phoneVisible = ref(false);
const status = ref(null);
const checkRef = ref("");
const phoneRef = ref("");
const passwordRef = ref();
const sms = ref();
const language = ref("zh-CN");
const data = reactive({
  queryParams: {
    phonenumber: "",
    password: "",
    systemLanguage: "1",
  },
  authentication: {
    phone: "",
    sms: "",
  },
  changePhone: {
    phone: "",
    sms: "",
  },
  changePhoneRules: {
    phone: [
      { required: true, message: "请输入手机号码", trigger: "blur" },
      {
        pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
        message: "请输入正确格式的手机号码",
        trigger: "blur",
      }
    ],
    sms: [
      { required: true, message: "请输入验证码", trigger: "blur" }
    ]
  },
  changePassword: {
    password: "",
    passwordAgain: "",
  },
  passwordRules: {
    password: [
      { required: true, message: "请输入新密码", trigger: "blur" },
      {
        pattern:
            /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,}$/,
        message: "密码需要为8到20之间的数字、字母和特殊字符混合组成",
        trigger: "blur",
      },
    ],
    passwordAgain: [
      { required: true, message: "请再次输入新密码", trigger: "blur" },
      {
        pattern:
            /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,}$/,
        message: "密码需要为8到20之间的数字、字母和特殊字符混合组成",
        trigger: "blur",
      },
    ],
  },
  userInfo: {},
  languageList: [],
});
const {
  queryParams,
  authentication,
  changePhone,
  userInfo,
  changePassword,
  passwordRules,
  languageList,
  changePhoneRules
} = toRefs(data);

function goBack() {
  proxy.$router.go(-1);
}

function getLanguageList() {
  getDicts("system_language").then((res) => {
    if (res.code === 200) {
      languageList.value = res.data;
    }
  });
}

function accountConfirm() {
  console.log(language.value, queryParams.value.systemLanguage)
  if (language.value != queryParams.value.systemLanguage) {
    locale.value = queryParams.value.systemLanguage;
    //存储到localstorage
    localStorage.setItem("currentLang", queryParams.value.systemLanguage);
    let params = {
      ...userInfo.value,
      systemLanguage: queryParams.value.systemLanguage,
    };
    updateUser(params).then((res) => {
      if (res.code === 200) {
        ElMessage.success($t("account.updateSuccess"));
        phoneVisible.value = false;
        language.value = queryParams.value.systemLanguage;
      } else {
        ElMessage.error($t("account.updateFail"));
        getPersonalInfo();
      }
    });
  }
}

// 手机号码更改
function phoneChange(val) {
  status.value = val; // 0-手机号码  1-密码
  checkVisible.value = true;
  authentication.value.sms = "";
}

// 发送手机号码验证码
function getSmsCode(val, phoneCode) {
  if (Waiting()) return;
  getSmsByPhone({
    phone: val === 0 ? authentication.value.phone : changePhone.value.phone,
  }).then((res) => {
    if (res.code === 200) {
      // console.log(res);
      Countdown();
    }else {
      ElMessage.success(res.msg);
    }
  });
}

// 获取验证码组件导出的方法
const Countdown = () => {
  sms.value.startCountdown();
};

const Waiting = () => {
  return sms.value.isWaiting;
};

// 身份验证
function checkConfirm() {
  if (authentication.value.sms !== "") {
    getSmsVerify(authentication.value).then((res) => {
      if (res.code === 200) {
        // console.log(res);
        changePassword.value.password = "";
        changePassword.value.passwordAgain = "";
        ElMessage.success($t("account.checkSuccess"));
        checkVisible.value = false;
        status.value == 1
          ? (passwordVisible.value = true)
          : (phoneVisible.value = true);
        changePhone.value.phone = "";
        changePhone.value.sms = "";
      } else {
        ElMessage.error($t("account.checkFail"));
      }
    });
  } else {
    ElMessage.error($t("account.notFilledIn"));
  }
}

// 更新密码验证
const passwordConfirm = async (passwordRef) => {
  if (!passwordRef) return;
  await passwordRef.validate((valid, fields) => {
    if (valid) {
      if (
        changePassword.value.password === changePassword.value.passwordAgain
      ) {
        let params = {
          newPassword: changePassword.value.password,
        };
        editPassword(params).then((res) => {
          if (res.code === 200) {
            ElMessage.success($t("account.updateSuccess"));
            passwordVisible.value = false;
            getPersonalInfo();
          } else {
            ElMessage.error($t("account.updateFail"));
          }
        });
      } else {
        ElMessage.error($t("account.checkAgain"));
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 更改手机号码验证
const phoneConfirm = async (phoneRef) => {
  if (!phoneRef) return
  await phoneRef.validate( async (valid, fields) => {
    if (valid) {
      await getSmsVerify(changePhone.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success($t("account.checkSuccess"));
          status.value == 1
              ? (passwordVisible.value = true)
              : (phoneVisible.value = true);
        } else {
          ElMessage.error($t("account.checkFail"));
        }
      });
      let params = {
        // ...userInfo.value,
        phonenumber: changePhone.value.phone,
      };
      await updateUser(params).then((res) => {
        if (res.code === 200) {
          ElMessage.success($t("account.updateSuccess"));
          phoneVisible.value = false;
          getPersonalInfo();
        } else {
          ElMessage.error($t("account.updateFail"));
          getPersonalInfo();
        }
      });
    } else {
      console.log('error submit!', fields)
    }
  })
}

function getPersonalInfo() {
  getInfo().then((res) => {
    if (res.code === 200) {
      // console.log(res);
      userInfo.value = res.user;
      let telArr = res.user.phonenumber.split("");
      telArr.splice(3, 4, "****");
      let result = telArr.join(""); //因为不会改变原数组，需要用一个新的变量去接收
      queryParams.value.phonenumber = result;
      // queryParams.value.phonenumber = res.user.phonenumber;
      authentication.value.phone = res.user.phonenumber;
      queryParams.value.systemLanguage = res.user.systemLanguage;
    }
  });
}

onMounted(() => {
  getPersonalInfo();
  getLanguageList();
});

onBeforeMount(() => {
  var lang = localStorage.getItem("currentLang");
  // console.log(lang);
});
</script>
<style lang="scss" scoped>
#myAccount {
  width: 100%;
  height: 100%;
}
.container {
  position: relative;
  width: calc(100% - 40px);
  height: 92%;
  margin: 0 20px 20px;
  border-radius: 10px;
  background: white;

  padding: 36px 30px 25px;
  .head-line {
    display: flex;
    align-items: center;
    img {
      margin-right: 12px;
    }
  }

  .personForm {
    width: 27%;
    position: relative;
    top: 15px;
    left: 27px;

    :deep .el-input {
      --el-input-height: var(--el-component-size);
      position: relative;
      font-size: var(--el-font-size-base);
      display: inline-flex;
      line-height: var(--el-input-height);
      box-sizing: border-box;
      vertical-align: middle;
      width: 320px;
      height: 40px;
    }

    .personTitle {
      font-size: 14px;
      color: #333333;
      font-weight: 500;
      margin-bottom: 10px;
      margin-top: 15px;
    }
    .personForm-container {
      display: flex;
      justify-content: space-between;
    }
    .createBtn {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 18px;
      width: 80px;
      height: 40px;
      font-size: 12px;
      box-sizing: border-box;
      border-radius: 4px;
      color: rgba(255, 255, 255, 1);
      background: rgba(43, 193, 123, 1);
      cursor: pointer;
    }
  }

  .down-container {
    position: absolute;
    right: 0;
    top: -5%;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    :deep .el-button {
      width: 81px;
      height: 32px;
    }
    :deep .el-button:nth-child(2) {
      background: #2bc17b;
      color: #ffffff;
    }
  }

  :deep .el-button {
    height: 36px;
  }

  .deviceVisible {
    width: 559px;
    height: 440px;
    position: relative;
    top: 20%;

    .title {
      height: 100%;
      background-color: #202741;
      color: #ffffff;
      text-align: left;
      padding: 15px 28px;
      font-size: 18px;
      letter-spacing: 1px;
    }

    .firstCheck {
      height: 36px;
    }

    .secondCheck {
      height: 36px;
      width: 70%;
    }

    :deep .el-input {
      --el-input-height: var(--el-component-size);
      position: relative;
      font-size: var(--el-font-size-base);
      display: inline-flex;
      line-height: var(--el-input-height);
      box-sizing: border-box;
      vertical-align: middle;
      //width: 100%;
      height: 40px;
    }
  }

  .passwordVisible {
    width: 559px;
    height: 440px;
    position: relative;
    top: 20%;

    .title {
      height: 100%;
      background-color: #202741;
      color: #ffffff;
      text-align: left;
      padding: 15px 28px;
      font-size: 18px;
      letter-spacing: 1px;
    }
  }

  .phoneVisible {
    width: 559px;
    height: 440px;
    position: relative;
    top: 20%;

    .title {
      height: 100%;
      background-color: #202741;
      color: #ffffff;
      text-align: left;
      padding: 15px 28px;
      font-size: 18px;
      letter-spacing: 1px;
    }

    .firstCheck {
      height: 36px;
    }

    .secondCheck {
      height: 36px;
      width: 70%;
    }

    :deep .el-input {
      --el-input-height: var(--el-component-size);
      position: relative;
      font-size: var(--el-font-size-base);
      display: inline-flex;
      line-height: var(--el-input-height);
      box-sizing: border-box;
      vertical-align: middle;
      //width: 100%;
      height: 40px;
    }
  }
}

:deep .el-form-item__content {
  display: flex;
  justify-content: space-between;
}

:deep .el-dialog__header {
  padding: 0;
  margin: 0;
}

:deep .el-dialog__body {
  padding: 20px calc(var(--el-dialog-padding-primary) + 30px) 30px;
}

:deep .el-dialog:not(.is-fullscreen) {
  margin-top: 30vh !important;
}

:deep .el-dialog__footer {
  padding-top: 0;
}
</style>
